package com.solo.system.service.impl;

import com.solo.common.core.base.service.impl.BasicServiceImpl;
import com.solo.common.core.utils.collection.CollUtils;
import com.solo.system.api.entity.SysRoleDept;
import com.solo.system.mapper.SysRoleDeptMapper;
import com.solo.system.mapper.SysRoleMapper;
import com.solo.system.model.role.SysRoleConvert;
import com.solo.system.model.role.SysRoleDeptConvert;
import com.solo.system.model.role.req.RoleDeptReq;
import com.solo.system.service.SysRoleDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 数据权限 Service实现类
 * @author 十一
 * @since 2024-11-07 09:18
 * 人生若只如初见，何事秋风悲画扇
 **/
@Service
@RequiredArgsConstructor
public class SysRoleDeptServiceImpl extends BasicServiceImpl<SysRoleDeptMapper, SysRoleDept> implements SysRoleDeptService {

    private final SysRoleMapper sysRoleMapper;
    private final SysRoleDeptMapper sysRoleDeptMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean assignData(RoleDeptReq req) {
        // 更新角色数据权限字段
        sysRoleMapper.update(SysRoleConvert.INSTANCE.convert(req));

        // 删除旧的角色部门关联
        sysRoleDeptMapper.deleteByRoleIds(Collections.singleton(req.getRoleId()));

        Set<Long> deptIdsIds = req.getDeptIds();
        if (CollUtils.isEmpty(deptIdsIds)) {
            return Boolean.TRUE;
        }
        // 批量保存新的角色部门关联
        return saveBatch(SysRoleDeptConvert.INSTANCE.convert(req));
    }

    @Override
    public Set<Long> selectDeptIds(Long roleId) {
        List<Long> menuIds = sysRoleDeptMapper.selectDeptIdsByRoleId(roleId);
        return new HashSet<>(menuIds);
    }

}
